<template>
	<div class="history">
		<div class="tabsBox">
			<div class="tabs" :class="classId === item.id && 'cho'" v-for="item in classList" :key="item.id"
				@click="typeChange(item)">{{ item.name }}</div>
		</div>
		{{ cTimer }}
		<button @click="addList">加入作品集合</button>

		<div class="imgListBox">
			<div class="img" :class="getImgClass(item)" v-for="item in imgList" :key="item.id" @click="imgCho(item)">
				<img :src="item.img" class="tabImg" mode="aspectFill" />
			</div>
		</div>
			<uni-pagination show-icon :page-size="pageSize" :current="pageCurrent" :total="total"
				@change="change" />
	</div>
</template>

<script>


export const getTimerFromDate = (timestamp, dateFormat) => {
	const date = new Date(timestamp); // 将时间戳转换为Date对象
	const days = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
	const map = {
		'YYYY': date.getFullYear(), // 年份
		'MM': date.getMonth() + 1, // 月份
		'DD': date.getDate(), // 日期
		'HH': date.getHours(), // 小时
		'mm': date.getMinutes(), // 分钟
		'ss': date.getSeconds(), // 秒
		'EEEE': days[date.getDay()],
	};

	return dateFormat.replace(/YYYY|MM|DD|HH|mm|ss|EEEE/g, match => {
		return map[match].toString().padStart(2, '0');
	});
}

export default {
	data() {
		return {
			imgChoList: [],
			imgList: [],
			classList: [],
			classId: '',
			// 每页数据量
			pageSize: 20,
			// 当前页
			pageCurrent: 1,
			// 数据总量
			total: 1000,
			loading: false
		}
	},
	   
	computed: {
		cTimer() {
			// return getTimerFromDate(new Date(), 'YYYY-MM-DD')
			return getTimerFromDate(new Date().getTime() + (24 * 60 * 60 * 1000), 'YYYY-MM-DD')
		},
	},
	mounted() {
		this.getClassList()
	},
	methods: {
		async addList() {

			let thumbList = []
			let imgList = []
			let previewList = []
			uni.showLoading({
				title: '加载中'
			});
			const saveImgToAlbum = (tempFilePath) => {
				var oA = document.createElement("a");
				oA.download = ''; // 设置下载的文件名，默认是'下载'
				oA.href = tempFilePath; //临时路径再保存到本地
				document.body.appendChild(oA);
				oA.click();
				oA.remove(); // 下载之后把创建的元素删除

			}
			// // 先下载数据
			// for (let index = 0; index < this.imgChoList.length; index++) {
			// 	try {
			// 		const {
			// 			thumb,
			// 			preview,
			// 			img,
			// 			id
			// 		} = this.imgChoList[index];

			// 		const res = await uni.downloadFile({
			// 			url: img,
			// 		})
			// 		console.log('res :>> ', res);
			// 		saveImgToAlbum(res.tempFilePath)
			// 	} catch (error) {

			// 	}
			// }
			const db = uniCloud.database()
			const pastDB = db.collection('photoTypeList')
			const typeInfo = this.classList.find(item => item.id === this.classId)
			for (let index = 0; index < this.imgChoList.length; index++) {
				try {
					const {
						thumb,
						preview,
						img,
						id,
						tag
					} = this.imgChoList[index];

					const timer = new Date().getTime()
					console.log(thumb);
					const thumbResult = await uniCloud.uploadFile({
						filePath: thumb,
						cloudPathAsRealPath: true,
						cloudPath: `outSideImgHis/${id}-${timer}-thumb.png`,
					});
					console.log('thumbResult',thumbResult);
					const imgResult = await uniCloud.uploadFile({
						filePath: img,
						cloudPathAsRealPath: true,
						cloudPath: `outSideImgHis/${id}-${timer}-img.png`,
					});
					const previewResult = await uniCloud.uploadFile({
						filePath: preview,
						cloudPathAsRealPath: true,
						cloudPath: `outSideImgHis/${id}-${timer}-preview.png`,
					});
					const regExp = new RegExp('cloud://env-00jxt14elvj6/', 'g');
					let addInfo = await pastDB.add({
						thumb: thumbResult.fileID.replace(regExp, ''),
						img: imgResult.fileID.replace(regExp, ''),
						preview: previewResult.fileID.replace(regExp, ''),
						type: typeInfo.name,
						tag
					})
					console.log('addInfo', addInfo)

					// thumbList.push(thumbResult.fileID.replace(regExp, ''))
					// imgList.push(imgResult.fileID.replace(regExp, ''))
					// previewList.push(previewResult.fileID.replace(regExp, ''))

				} catch (error) {
					console.log(error);
				}
			}

			// let imgInfo = {
			// 	thumb: thumbList,
			// 	img: imgList,
			// 	preview: previewList
			// }
			// const db = uniCloud.database()
			// const pastDB = db.collection('pastPhotoList')
			// const typeInfo = this.classList.find(item => item.id === this.classId)
			// let addInfo = await pastDB.add({
			// 	imgIdInfo: imgInfo,
			// 	type: typeInfo.name,
			// 	createTime: this.cTimer,
			// })
			uni.hideLoading();





		},
		getImgClass(item) {
			const isHave = this.imgChoList.find(cItem => cItem.id === item.id)
			return isHave && 'imgCho'
		},
		imgCho(item) {
			const isHaveInx = this.imgChoList.findIndex(cItem => cItem.id === item.id)
			if (isHaveInx === -1) {
				this.imgChoList.push(item)
			} else {
				this.imgChoList.splice(isHaveInx, 1)
			}
		},
		typeChange(item) {
			this.classId = item.id
			this.total = item.count
			this.pageCurrent = 1
			this.imgList = []
			this.getImgList()
		},
		// 多选
		selectionChange(e) {
			console.log(e.detail.index)
			this.selectedIndexs = e.detail.index
		},
		// 分页触发
		change(e) {
			this.pageCurrent = e.current
			console.log('e.current', e.current)
			this.getImgList()
		},
		async getImgList() {
			const {
				statusCode,
				data
			} = await uni.request({
				url: `http://service.picasso.adesk.com/v1/vertical/category/${this.classId}/vertical`,
				method: 'GET',
				data: {
					limit: this.pageSize,
					skip: (this.pageCurrent - 1) * this.pageSize,
					order: 'hot'
				},
			})
			console.log('data :>> ', data);
			this.imgList = this.imgList.concat(data.res.vertical)

		},
		getClassList() {
			const that = this
			uni.request({
				url: 'http://service.picasso.adesk.com/v1/vertical/category',
				method: 'GET',
				success: function (res) {
					const {
						data
					} = res
					that.classList = data.code === 0 ? data.res.category : []
					that.classId = that.classList[0].id
					that.total = that.classList[0].count
					that.getImgList()
				},
				fail: function (err) {
					console.log('请求失败', err);
				}
			});
		},

	},
}
</script>
<style scoped lang='less'>
.tabsBox {
	display: flex;

	>.tabs {
		margin-top: 20px;
		margin-right: 10px;
		height: 32px;
		line-height: 32px;
		text-align: center;
		padding: 0 6px;
		border: 1px solid #000;
		cursor: pointer;
	}

	>.cho {
		background-color: yellow;
	}
}

.imgListBox {
	width: 100%;
	display: flex;
	flex-wrap: wrap;

	>.img {
		width: 320px;

		img {
			width: 100%;
		}
	}

	>.imgCho {
		border: 6px solid green;

		img {
			width: 100%;
		}
	}
}
</style>